<template>
  <div>
    <el-dialog
      title="分配权限"
      width="50%"
      :visible.sync="isVisible"
      @close="closeDialog"
      @open="openDialog"
    >
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <!-- 按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'SetRightDialog',
  data() {
    return {
      isVisible: false,
      rightslist: [],
      // 默认选中的节点
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      // 当前roleid
      roleId: ''
    }
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    bindrole: {
      type: Object
    }
  },
  watch: {
    show() {
      this.isVisible = this.show
    },
    bindrole() {
      this.roleId = this.bindrole.id
    }
  },
  methods: {
    // 关闭时回调
    closeDialog() {
      this.$emit('update:show', false)
      this.defKeys = []
    },
    // 打开时回调
    openDialog() {
      console.log('openDialog')
      this.getRightList()
      console.log('role:', this.role)
      this.getLeafKeys(this.bindrole)
    },
    // 获取权限数据
    async getRightList() {
      const { data: res } = await this.$http.get('rights/tree')

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.rightslist = res.data

      console.log('getRightList:', this.rightslist)
      // 递归获取三级节点idlist
      // this.getLeafKeys(this.defKeys)
    },
    getLeafKeys(item) {
      // 递归获取id，保存到defKeys数组中
      if (!item.children) {
        return this.defKeys.push(item.id)
      }
      item.children.forEach(item => this.getLeafKeys(item))
    },
    async save() {
      // console.log('defKeys:', this.defKeys)
      console.log(this.$refs.treeRef.getCheckedKeys())
      console.log(this.$refs.treeRef.getHalfCheckedKeys())
      const keys = [
        this.$refs.treeRef.getCheckedKeys(),
        this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)
      const ids = keys.join(',')

      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: ids })
      console.log('save:', res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.$emit('get-role-list')
    }
  }
}
</script>

<style lang="less" scoped></style>
